package cn.zc.Scheduled;

import cn.zc.constant.MessageConstant;
import cn.zc.entity.LateTimeCource;
import cn.zc.entity.ScheduledTaskInfo;
import cn.zc.entity.TimeVo;
import cn.zc.mapper.CourceMapper;
import cn.zc.service.CourceService;
import cn.zc.service.impl.PeriodTimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import java.util.concurrent.locks.Lock;
import java.util.List;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.locks.ReentrantLock;
import java.util.ArrayList;

@Component
public class DynamicScheduleTask implements SchedulingConfigurer {

    @Autowired
    private TaskScheduler taskScheduler;
    @Autowired
    private CourceService courceService;
    @Autowired
    private CourceMapper courceMapper;

    @Autowired
    private PeriodTimeService periodTimeService;  // 自定义的服务用于读取数据库中的时间段


    private final List<ScheduledFuture<?>> scheduledTasks = new ArrayList<>();
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        List<TimeVo> periodTimes = periodTimeService.getAllPeriodTimes();

        for (TimeVo periodTime : periodTimes) {

            String startTime = periodTime.getStart_time();  // 比如 "08:00"
            Trigger trigger1 = trigger(startTime);
            // 解析 startTime 为 Cron 表达式或者指定触发器
            ScheduledFuture<?> scheduledTask = taskScheduler.schedule(() -> {
                checkForLateSignins(periodTime);
            }, trigger1);
            scheduledTasks.add(scheduledTask);
        }
    }

    private Trigger trigger(String startTime) {
        return new CronTrigger(getCronExpression(startTime));
    }

    // 生成 cron 表达式
    private String getCronExpression(String startTime) {
        LocalTime time = LocalTime.parse(startTime, DateTimeFormatter.ofPattern("HH:mm"));
        return String.format("0 %d %d * * ?", time.getMinute(), time.getHour());
    }

    // 签到检查逻辑
    private void checkForLateSignins(TimeVo timeVo) {
        // 在此处执行将未签到用户标记为迟到的逻辑
        int period = timeVo.getPeriod();
//        System.out.println("第"+period+"节");
        //获得当前是周几
        DayOfWeek dayOfWeek = LocalDate.now().getDayOfWeek();
        int dayOfWeekValue = dayOfWeek.getValue();
        System.out.println("周"+dayOfWeekValue);
        courceService.lateTime(period, dayOfWeekValue);
        //向违纪表中添加数据
        List<LateTimeCource> lateTimeCources = courceService.selectlateTime(period, dayOfWeekValue);
        for (LateTimeCource lateTimeCource : lateTimeCources) {
            //默认违纪是迟到
            lateTimeCource.setViolation_content(MessageConstant.Late);
            lateTimeCource.setDayOfWeek(dayOfWeekValue);
            lateTimeCource.setWeek(courceMapper.getWeek());
            courceService.addLateTimeCource(lateTimeCource);
            System.out.println("成功添加"+lateTimeCource);
        }
    }

    // 如果需要重新更新定时任务
    public void resetTasks() {
//        if (scheduledTask != null) {
//            scheduledTask.cancel(false);
//        }
//        configureTasks(null);  // 重新加载任务
//        int taskCount = getTaskCount();
//        System.out.println(taskCount);
        // 获取所有已存在的定时任务

        // 取消所有已存在的定时任务
        for (ScheduledFuture<?> task : scheduledTasks) {
            cancelScheduledTask(task);
        }

        // 获取新的时间段信息
        List<TimeVo> newPeriodTimes = periodTimeService.getAllPeriodTimes();

        // 添加新的定时任务
        for (TimeVo periodTime : newPeriodTimes) {
            addNewScheduledTask(periodTime);
        }
    }
    public void addNewScheduledTask(TimeVo periodTime) {
        String startTime = periodTime.getStart_time();
        Trigger trigger1 = trigger(startTime);
        ScheduledFuture<?> schedule = taskScheduler.schedule(() -> {
            checkForLateSignins(periodTime);
        }, trigger1);
        scheduledTasks.add(schedule);
    }
    public void cancelScheduledTask(ScheduledFuture<?> scheduledTask) {
        if (scheduledTask != null && !scheduledTask.isCancelled()) {
            scheduledTask.cancel(false);
        }
    }
}
